package com.budwk.app.sqfwV2.generator.shawenTown.excel;

import cn.hutool.core.collection.CollectionUtil;
import cn.hutool.core.date.DateUtil;
import com.alibaba.fastjson.JSONObject;
import com.budwk.app.sqfw.constants.CommonConstants;
import com.budwk.app.sqfw.models.Sqfw_formSummary_new;
import com.budwk.app.sqfwDoc.bo.SqfwExcelForSummaryBO;
import com.budwk.app.sqfwDoc.bo.SqfwExcelJudgeRes;
import com.budwk.app.sqfwDoc.codeGenerator.excelGenerate.BaseExcelParamDTO;
import com.budwk.app.sqfwDoc.codeGenerator.excelGenerate.BaseTemplateExcelGenerator;
import com.budwk.app.sqfwDoc.codeGenerator.excelGenerate.SqfwExcelCreateCommonBO;
import com.budwk.app.sqfwV2.component.DayingRoadPdfComponent;
import com.budwk.app.sqfwV2.component.ShawenTownComponent;
import com.budwk.app.sqfwV2.dto.image.ExcelProblemImageConfigBO;
import com.budwk.app.sqfwV2.dto.shawenTown.SWTownProblemVo;
import com.budwk.app.sqfwV2.dto.shawenTown.ShawenTownSafetyPdfDTO;
import com.budwk.app.sqfwV2.dto.shawenTown.ShawenTownSafetyProblemVo;
import com.budwk.app.sqfwV2.enums.FileServiceConfigEnum;
import com.budwk.app.util.StrUtil;
import com.budwk.app.util.poiUtils.excelPictureConfigBO.ExcelFileCreateParamBO;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;

import java.math.BigDecimal;
import java.util.*;
import java.util.stream.Collectors;

/**
 * @author 贵阳市电动自行车排查整治台账
 * @since 2024-03-11
 *
 * 沙文消防安全排查 ShawenTownSafety
 * 村（居）电动自行车排查整治台账.xlsx
 */

@Slf4j
public class ElectricBicycleLedgerGenerator extends BaseTemplateExcelGenerator {

    @Override
    protected String getTemplateName() {
        return FileServiceConfigEnum.BYA.getFilePath();
    }

    @Override
    public String getDownloadFileName() {
        return FileServiceConfigEnum.BYA.getFileName();
    }

    /**
     * 用户自定义excel基础参数，比如表头这样的公用数据
     * @param excelParam 已经填充的基础数据据
     * @param excelCreateParam excel生成提供的原料
     */
    @Override
    protected void customerPopularSheetBaseParam(Map<String, Object> excelParam, SqfwExcelCreateCommonBO excelCreateParam) {
        log.info("ElectricBicycleLedgerGenerator getBaseExcelParamDTO: {}", JSONObject.toJSONString(excelCreateParam.getBaseExcelParamDTO()));
        BaseExcelParamDTO baseParam = excelCreateParam.getBaseExcelParamDTO();
        // 获取数据
        List<Sqfw_formSummary_new> summaryList = ShawenTownComponent.getSummaryList(excelCreateParam);
        // 填报单位
        String unitName = String.format("%s%s%s%s%s", StrUtil.formatStr(baseParam.getProvince()), StrUtil.formatStr(baseParam.getCity())
                , StrUtil.formatStr(baseParam.getDistrict()), StrUtil.formatStr(baseParam.getCounty())
                , StrUtil.formatStr(baseParam.getCommunity()));
        excelParam.put("unitName", unitName);
        // 签名
        ShawenTownComponent.excelSignature(baseParam.getCreateUserSigUrl(), baseParam.getCreateUserName(), excelParam);
        // 统计周期
        excelParam.put("checkedUnitLeaderStr", StrUtil.formatStr(baseParam.getCreateUserName()));
        excelParam.put("startMonth", "-");
        excelParam.put("startDay", "-");
        excelParam.put("endMonth", "-");
        excelParam.put("endDay", "-");
        if (summaryList.size() > 0) {
            // 因为数据是按照时间降序的 所以最后一条数据为开始时间
            Sqfw_formSummary_new startData = summaryList.get(summaryList.size() - 1);
            Sqfw_formSummary_new endData = summaryList.get(0);
            String startMonth = DateUtil.format(startData.getFillDate(), "MM");
            String startDay = DateUtil.format(startData.getFillDate(), "dd");
            String endMonth = DateUtil.format(endData.getFillDate(), "MM");
            String endDay = DateUtil.format(endData.getFillDate(), "dd");
            excelParam.put("startMonth", startMonth);
            excelParam.put("startDay", startDay);
            excelParam.put("endMonth", endMonth);
            excelParam.put("endDay", endDay);
        }
    }

    /**
     * 构造内容体
     * @param listMap
     * @param excelCreateParam
     */
    @Override
    protected void customerPopularSheetDataParam(List<Map<String, Object>> listMap, SqfwExcelCreateCommonBO excelCreateParam) {
        List<Sqfw_formSummary_new> summaryList = DayingRoadPdfComponent.getSummaryList(listMap, excelCreateParam);
        log.info("ElectricBicycleLedgerGenerator customerDataParam summaryList:  {}", JSONObject.toJSONString(summaryList));
        List<Sqfw_formSummary_new> results = generateNewData(summaryList);
        // 按照任务分组统计
        List<String> communitys = results.stream().map(Sqfw_formSummary_new::getCommunity).distinct().collect(Collectors.toList());
        for (String community : communitys) {
            listMap.add(buildExcelMap(community, results));
        }
        log.info("ElectricBicycleLedgerGenerator customerDataParam end: {}", JSONObject.toJSONString(listMap));
    }

    @Override
    public List<Sqfw_formSummary_new> generateNewData(List<Sqfw_formSummary_new> summaryList) {
        if (CollectionUtil.isEmpty(summaryList)) {
            return summaryList;
        }
        List<Sqfw_formSummary_new> newList = new ArrayList<>();
        for (Sqfw_formSummary_new summary : summaryList) {
            ShawenTownSafetyPdfDTO roadPdfDTO = JSONObject.parseObject(summary.getParamData(), ShawenTownSafetyPdfDTO.class);
            // 是否有电动自行车 = 是 时生成表格
            ShawenTownSafetyProblemVo electricBicycle = roadPdfDTO.getElectricBicycle();
            if (electricBicycle != null) {
                if (CommonConstants.TRUE.equals(electricBicycle.getKey())) {
                    newList.add(summary);
                }
            }
        }
        return newList;
    }

    private Map<String, Object> buildExcelMap(String community, List<Sqfw_formSummary_new> results) {
        List<SWTownProblemVo> sevenList = ShawenTownComponent.getSevenDefaults();
        List<SWTownProblemVo> fourList = ShawenTownComponent.getElecFourDefaults();
        List<Sqfw_formSummary_new> datas = results.stream().filter(e -> e.getCommunity().equals(community)).collect(Collectors.toList());
        Map<String, Object> map = new HashMap<>(20);
        map.put("community", StrUtil.formatStr(datas.get(0).getCommunity())); //地区、部门
        map.put("checkTaskNum", datas.size()); // 组织检查组

        Set<String> summaryNum = new HashSet<>(); // 检查单位场所 按照地址去重
        List<String> checkPersons = new ArrayList<>(); // 组织检查人员 同行人+提交人
        int isParkeCharged = 0; // 电动自行车区域停放、充电：计算所有巡查记录中的“否”
        int whetherElectricParked = 0; // 电动自行车“进楼入户人车同屋”
        int isFlyLineCharging = 0; // “飞线充电”
        int isEvacuationRoutes = 0; // "电动自行车占用、 堵塞、疏散通道"
        int isModification = 0; // 擅自改装 原厂配件
        int isPowerBattery = 0; // "私自更换大功率蓄电池"
        int isRemovesKeyComponents = 0; //  拆除限速器等关键性组件
        int stopBusinessForRectification = 0; //  停业整顿
        int sealOff = 0; //  查封关闭企业
        int issueARectificationNotice = 0; //  下达整改意见
        BigDecimal penaltyAmount = new BigDecimal(0); //  罚款
        for (Sqfw_formSummary_new formSummary : datas) {
            ShawenTownSafetyPdfDTO pdfDTO = JSONObject.parseObject(formSummary.getParamData(), ShawenTownSafetyPdfDTO.class);
            List<SWTownProblemVo> params = pdfDTO.getElectricBicycle().getParams();
            if (params == null || params.size() == 0) {
                continue;
            }
            String peers = pdfDTO.getPeers();
            if (StringUtils.isNotEmpty(peers)) {
                checkPersons.addAll(List.of(peers.split(",")));
            }
            if (StringUtils.isNotEmpty(formSummary.getCreateBy())) {
                checkPersons.add(formSummary.getCreateBy());
            }
            summaryNum.add(pdfDTO.getAddress());
            isParkeCharged = isParkeCharged + calNum(params, ShawenTownComponent.getElecProblemByNumber(sevenList, "1"));
            whetherElectricParked = whetherElectricParked + calNum(params, ShawenTownComponent.getElecProblemByNumber(sevenList, "2"));
            isFlyLineCharging = isFlyLineCharging + calNum(params, ShawenTownComponent.getElecProblemByNumber(sevenList, "3"));
            isEvacuationRoutes = isEvacuationRoutes + calNum(params, ShawenTownComponent.getElecProblemByNumber(sevenList, "4"));
            isModification = isModification + calNum(params, ShawenTownComponent.getElecProblemByNumber(sevenList, "5"));
            isPowerBattery = isPowerBattery + calNum(params, ShawenTownComponent.getElecProblemByNumber(sevenList, "6"));
            isRemovesKeyComponents = isRemovesKeyComponents + calNum(params, ShawenTownComponent.getElecProblemByNumber(sevenList, "7"));

            stopBusinessForRectification = stopBusinessForRectification + calNum(params, ShawenTownComponent.getElecProblemByNumber(fourList, "2"));
            sealOff = sealOff + calNum(params, ShawenTownComponent.getElecProblemByNumber(fourList, "4"));
            issueARectificationNotice = issueARectificationNotice + calRectificationNotice(params, ShawenTownComponent.getElecProblemByNumber(fourList, "1"));
            // 罚款
            BigDecimal penaltyAmount1 = ShawenTownComponent.getPenaltyAmount(params, ShawenTownComponent.getElecProblemByNumber(fourList, "3"));
            if (penaltyAmount1 != null) {
                penaltyAmount = penaltyAmount.add(penaltyAmount1);
            }
        }
        map.put("summaryNum", summaryNum.size()); // 检查单位场所 按照地址去重
        map.put("checkPersons", checkPersons.size());  // 组织检查人员： 同行人+提交人
        map.put("isParkeCharged", isParkeCharged); // "电动自行车区域停放、充电"
        map.put("whetherElectricParked", whetherElectricParked); // 电动自行车“进楼入户人车同屋”
        map.put("isFlyLineCharging", isFlyLineCharging); // “飞线充电”
        map.put("isEvacuationRoutes", isEvacuationRoutes); // "电动自行车占用、 堵塞、疏散通道"
        map.put("isModification", isModification); // 擅自改装 原厂配件
        map.put("isPowerBattery", isPowerBattery); // "私自更换大功率蓄电池"
        map.put("isRemovesKeyComponents", isRemovesKeyComponents); // 拆除限速器等关键性组件
        map.put("stopBusinessForRectification", stopBusinessForRectification); // 停业整顿
        map.put("sealOff", sealOff); // 查封关闭企业
        map.put("penaltyAmount", penaltyAmount); // 罚款
        map.put("issueARectificationNotice", issueARectificationNotice); //  下达整改意见
        if (penaltyAmount.equals(new BigDecimal(0))) {
            map.put("penaltyAmount", "-"); // 罚款
        }
        return map;
    }

    // 下达整改意见
    private Integer calRectificationNotice(List<SWTownProblemVo> params, SWTownProblemVo recOne) {
        Optional<SWTownProblemVo> optional = params.stream().filter(e -> e.getFields().equals(recOne.getFields())).findFirst();
        if (optional.isPresent()) {
            if (optional.get().getKey().equals(recOne.getKey())) {
                return 1;
            }
        }
        return 0;
    }


    /**
     * 计算和默认值不一致的情况
     * @param params
     * @return
     */
    private Integer calNum(List<SWTownProblemVo> params, SWTownProblemVo p) {
        Optional<SWTownProblemVo> optional = params.stream().filter(e -> e.getFields().equals(p.getFields())).findFirst();
        if (optional.isPresent()) {
            if (!optional.get().getKey().equals(p.getKey())) {
                return 1;
            }
        }
        return 0;
    }



    @Override
    protected void completeExcelFileCreateParam(ExcelFileCreateParamBO excelFileCreateParam) {

    }

    @Override
    protected void customerPopularRowDataMap(Map<String, Object> rowDataMap, SqfwExcelForSummaryBO forSummaryBO) {

    }

    @Override
    protected SqfwExcelJudgeRes judgeDataIntoExcelBeforeErgodic(SqfwExcelCreateCommonBO excelCreateParam, Map<String, Object> excelParam) {
        return null;
    }

    @Override
    protected SqfwExcelJudgeRes judgeDataIntoExcelBeforeCreate(Map<String, Object> excelParam) {
        return null;
    }

    @Override
    protected Class<?> getImageConfigBO() {
        return ExcelProblemImageConfigBO.class;
    }
}
